package edu.zjucst.spb.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.zjucst.spb.dao.mapper.StageMapper;
import edu.zjucst.spb.domain.entity.Stage;
import edu.zjucst.spb.service.StageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author ZlunYan
 * @description
 * @create 2023-11-28
 */

@Service
public class StageServiceImpl implements StageService {

    @Autowired
    private StageMapper stageMapper;

    @Override
    public int insertStage(Stage stage) {
        // TODO 学工号应该不能重复
        return stageMapper.insert(stage);
    }

    @Override
    public Stage getStageByUserId(String userId) {
        QueryWrapper<Stage> wrapper = new QueryWrapper<>();
        wrapper.eq("user_number", userId);

        return stageMapper.selectOne(wrapper);
    }

    @Override
    public IPage<Stage> selectStageList(Page<Stage> page, Integer developId, String userName, String userNumber,
                                        Integer dateType, Date startTime, Date endTime) {

        QueryWrapper<Stage> wrapper = new QueryWrapper<>();
        if(developId!=null){
            wrapper.eq("development_phase_id",developId);
        }
        if(userName!=null){
            wrapper.eq("user_name",userName);
        }
        if(userNumber!=null){
            wrapper.eq("user_number",userNumber);
        }
        if (dateType!=null && dateType >= 0) {
            if (startTime != null) {
                if (endTime != null) {
                    wrapper.between(DateTypeMapper.getDateType2Str().get(dateType), startTime, endTime);
                } else {
                    wrapper.ge(DateTypeMapper.getDateType2Str().get(dateType), startTime);
                }
            } else if (endTime != null) {
                wrapper.le(DateTypeMapper.getDateType2Str().get(dateType), endTime);
            }
        }

        Page<Stage> stagePage = stageMapper.selectPage(page, wrapper);
        // TODO 加入权限判断
        return stagePage;
    }

    @Override
    public void updateStageByUserId(Stage stage, String userId) {
        QueryWrapper<Stage> wrapper = new QueryWrapper<>();
        wrapper.eq("user_number", userId);

        stageMapper.update(stage, wrapper);
    }

    @Override
    public List<Stage> getStageByDateRange(String dateCol, Date startTime, Date endTime) throws ParseException {
        QueryWrapper<Stage> wrapper = new QueryWrapper<>();



        wrapper.between(dateCol, startTime, endTime);
        return stageMapper.selectList(wrapper);
    }

    @Override
    public List<Stage> getStageByDateStrRange(String dateCol, String startStr, String endStr) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(startStr);
        Date endDate = sdf.parse(endStr);

        return getStageByDateRange(dateCol, startDate, endDate);
    }

    static private class DateTypeMapper {
        private static final List<String> dateType2Str = Arrays.asList(
            "birthday",
            "delivery_time"
        );

        public static List<String> getDateType2Str() {
            return dateType2Str;
        }
    }
}

//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import edu.zjucst.spb.dao.mapper.StageMapper;
//import edu.zjucst.spb.domain.entity.Branch;
//import edu.zjucst.spb.domain.entity.Role;
//import edu.zjucst.spb.domain.entity.SpbUser;
//import edu.zjucst.spb.domain.entity.Stage;
//import edu.zjucst.spb.service.BranchService;
//import edu.zjucst.spb.service.RoleService;
//import edu.zjucst.spb.service.SpbUserService;
//import edu.zjucst.spb.service.StageService;
//import edu.zjucst.spb.util.BranchUtil;
//import edu.zjucst.spb.util.SessionUtil;
//import edu.zjucst.spb.util.StageUtil;
//import org.apache.shiro.authz.AuthorizationException;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Calendar;
//import java.util.Date;
//import java.util.List;
//
//import static edu.zjucst.spb.constant.StageConstant.APPLICANT;
//
//@Service
//public class StageServiceImpl implements StageService {
//
//    @Autowired
//    private StageMapper stageMapper;
//
//    @Autowired
//    private SpbUserService spbUserService;
//
//    @Autowired
//    private RoleService roleService;
//
//    @Autowired
//    private BranchService branchService;
//
//
//    @Override
//    public IPage<Stage> selectStageList(Page<Stage> page, String developmentPhase, String userName, String userNumber,
//                                        Integer queryByDate, Date startTime, Date endTime) {
//        QueryWrapper<Stage> wrapper = new QueryWrapper<>();
//        if(developmentPhase!=null){
//            wrapper.eq("development_phase",developmentPhase);
//        }
//        if(userName!=null){
//            wrapper.eq("user_name",userName);
//        }
//        if(userNumber!=null){
//            wrapper.eq("user_number",userNumber);
//        }
//
//        if (queryByDate != null && queryByDate > 0) {
//            if (queryByDate == 1) {
//                // 入党申请书递交时间
//                wrapper.between("delivery_time", startTime, endTime);
//            } else if (queryByDate == 2) {
//                // 成为积极分子时间
//                wrapper.between("activist_time", startTime, endTime);
//            } else if (queryByDate == 3) {
//                // 成为发展对象时间
//                wrapper.between("confirm_time", startTime, endTime);
//            } else if (queryByDate == 4) {
//                // 成为预备党员时间
//                wrapper.between("branch_prepare_time", startTime, endTime);
//            }
//        }
//
//        Page<Stage> stagePage = stageMapper.selectPage(page, wrapper);
//
//        // TODO: 权限判断，非支部书记、党委、团委老师不能使用这个功能
//        Role role = roleService.findRoleById(SessionUtil.getRoleId());
//
//        // 如果是支部书记 则筛选支部
//        if(role.getRoleName().equals("支部书记")){
//            Branch branch = branchService.findBranchById(SessionUtil.getBranchId());
//
//            List<Stage> stages = new ArrayList<>();
//            for (Stage stage:stagePage.getRecords()
//            ) {
//                SpbUser user = spbUserService.findUserByNumber(stage.getUserNumber());
//                if(BranchUtil.checkBranch(user,branch.getBranchName())){
//                    stages.add(stage);
//                }
//            }
//            stagePage.setRecords(stages);
//        }
//
//        return stagePage;
//    }
//
//
//
//
//    @Override
//    public int updateStage(Stage stage) {
//        Stage oldStage = selectStageByNumber(stage.getUserNumber());
//        if(stage.getId()==null){
//            stage.setId(oldStage.getId());
//        }
//        Role role = roleService.findRoleById(SessionUtil.getRoleId());
//        //防止前端状态错误
//        stage.setState(oldStage.getState());
//        //更新可以直接设置的字段 资格审查间隔，团员身份，思想汇报，教育考察登记表，
//        Stage simpleEditableStage = StageUtil.simpleEditableStage(stage,role.getRoleName());
//        stageMapper.updateById(simpleEditableStage);
//        //根据状态更新部分字段
//        Stage status = StageUtil.isFieldEditableForPhaseStatus(stage,role.getRoleName());
//        //更新了发展阶段
//        if(status.getDevelopmentPhase()!=null){
//            SpbUser spbUser = spbUserService.findUserByNumber(stage.getUserNumber());
//            spbUser.setDevelopmentPhase(spbUser.getDevelopmentPhase());
//            spbUserService.updateUser(spbUser);
//        }
//        stageMapper.updateById(status);
//        return 1;
//    }
//
//
//
//    @Override
//    public int insert(Stage stage) {
//        Stage newStage = new Stage();
//        newStage.setUserNumber(stage.getUserNumber());
//        newStage.setUserName(stage.getUserName());
//        newStage.setDevelopmentPhase(APPLICANT);
//        return stageMapper.insert(newStage);
//    }
//
//    @Override
//    public Stage selectStageByNumber(String userNumber) {
//        QueryWrapper<Stage> wrapper = new QueryWrapper<>();
//        wrapper.eq("user_number",userNumber);
//        return stageMapper.selectOne(wrapper);
//    }
//
//    @Override
//    @Transactional
//    public int editStageList(List<Stage> stageList) {
//        int res = 0;
//        Role role = roleService.findRoleById(SessionUtil.getRoleId());
//        Branch branch = branchService.findBranchById(SessionUtil.getBranchId());
//        for (Stage stage:stageList) {
//            if(role.getRoleName().equals("支部书记")){
//                SpbUser user = spbUserService.findUserByNumber(stage.getUserNumber());
//                if(!BranchUtil.checkBranch(user,branch.getBranchName())){
//                    continue;
//                }
//            }
//            if(selectStageByNumber(stage.getUserNumber())!=null){
//                res += updateStage(stage);
//            }else{
//                if(!role.getRoleName().equals("学院党委") && !role.getRoleName().equals("学院团委")){
//                    throw new AuthorizationException();
//                }
//                res += insert(stage);
//            }
//        }
//        return res;
//    }
//
//    @Override
//    public int updateStageList(List<Stage> stageList) {
//        int res = 0;
//        Role role = roleService.findRoleById(SessionUtil.getRoleId());
//
//        if (!(role.getRoleName().equals("支部书记") || role.getRoleName().equals("学院团委") || role.getRoleName().equals("学院党委"))) throw new AuthorizationException();
//        Branch branch = null; if (role.getRoleName().equals("支部书记")) branch = branchService.findBranchById(SessionUtil.getBranchId());
//
//        for (Stage stage:stageList) {
//            if(role.getRoleName().equals("支部书记")){
//                SpbUser user = spbUserService.findUserByNumber(stage.getUserNumber());
//                assert branch != null;
//                if(!BranchUtil.checkBranch(user,branch.getBranchName())) continue;
//            }
//
//            if(selectStageByNumber(stage.getUserNumber())!=null) res += updateStage(stage);
//        }
//
//        return res;
//    }
//
//    @Override
//    public int insertStageList(List<Stage> stageList) {
//        int res = 0;
//        Role role = roleService.findRoleById(SessionUtil.getRoleId());
//
//        if(!role.getRoleName().equals("学院党委") && !role.getRoleName().equals("学院团委")){
//            throw new AuthorizationException();
//        }
//
//        for (Stage stage:stageList) res += insert(stage);
//        return res;
//    }
//
//    @Override
//    @Transactional
//    public int deleteStageList(List<String> userNumber) {
//        Role role = roleService.findRoleById(SessionUtil.getRoleId());
//        if(!role.getRoleName().equals("学院党委") && !role.getRoleName().equals("学院团委")){
//            throw new AuthorizationException();
//        }
//        int cnt = 0;
//        QueryWrapper<Stage> wrapper = new QueryWrapper<>();
//        for (String number:userNumber
//             ) {
//            wrapper.clear();
//            wrapper.eq("user_number",number);
//            cnt += stageMapper.delete(wrapper);
//        }
//        return cnt;
//    }
//}
